package cn.controller;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import cn.common.ExceResult;
import cn.common.LayTable;
import cn.filter.LoginCheck;
import cn.kpi.entity.sys.OrgEntity;
import cn.kpi.entity.sys.UserEntity;
import cn.kpi.entity.usualassessment.UsAssTemplateIndexEntity;
import cn.kpi.entity.vtiondpline.VtDpItemEntity;
import cn.kpi.entity.vtiondpline.VtDpUserEntity;
import cn.kpi.entity.vtiondpline.VtDpUserListEntity;
import cn.kpi.entity.vtiondpline.VtDpUserLogEntity;
import cn.kpi.service.sys.IOrgService;
import cn.kpi.service.sys.IUserService;
import cn.kpi.service.vtiondpline.IVtDpItemService;
import cn.kpi.service.vtiondpline.IVtDpUserService;

@Controller
@RequestMapping("vtdpuser")
public class VtDpUserController extends BaseController {
    @Autowired
    private IVtDpUserService iVtDpUserService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IVtDpItemService iVtDpItemService;

    @Autowired
    private IOrgService iOrgService;

    @RequestMapping(value = "/user_vtdp_list")
    public String UserVtdpList(Model model) {
        try {
            //List<OrgEntity> orglst = iOrgService.GetOrgList();
//			String where=this.GetLoginUserOrgidWhereForOrg();
//			List<OrgEntity> orglst = iOrgService.GetOrgListByWhere(where);
//			for (int i = 0; i < orglst.size(); i++) {
//				String html="";
//				for(int j=0;j<orglst.get(i).getLevel();j++){
//					html+="&#12288;";
//				}
//				orglst.get(i).setOrgname(html+orglst.get(i).getOrgname());
//			}
//			model.addAttribute("orglst", orglst);
            Calendar cale = Calendar.getInstance();
            int year = cale.get(Calendar.YEAR);
            model.addAttribute("year", year);
        } catch (Exception ex) {

        }

        return "vtiondpline/user_vtdp_list";
    }


    @RequestMapping(value = "/user_vtdp__gd_list")
    public String UserVtdpGdList(Model model) {
        try {
//			String where=this.GetLoginUserOrgidWhereForOrg();
//			List<OrgEntity> orglst = iOrgService.GetOrgListByWhere(where);
//			for (int i = 0; i < orglst.size(); i++) {
//				String html="";
//				for(int j=0;j<orglst.get(i).getLevel();j++){
//					html+="&#12288;";
//				}
//				orglst.get(i).setOrgname(html+orglst.get(i).getOrgname());
//			}
//			model.addAttribute("orglst", orglst);

            Calendar cale = Calendar.getInstance();
            int year = cale.get(Calendar.YEAR);
            model.addAttribute("year", year);
            UserEntity userEntity = this.GetLoginUser();
            if (userEntity.getRealname().contains("开发")) {

                model.addAttribute("isadmin", true);
            } else {
                model.addAttribute("isadmin", false);

            }
        } catch (Exception ex) {

        }

        return "vtiondpline/user_vtdp_gd_list";
    }

    @RequestMapping(value = "/user_vtdp_edit")
    public String UserVtdpEdit(Model model, Long uservtdpid) {
        try {
            String where = this.GetLoginUserForUserListWhere();
            List<UserEntity> userlst = iUserService.GetUserListByWhere("");
            model.addAttribute("userlst", userlst);

            List<VtDpItemEntity> vtdpitemlst = iVtDpItemService.GetVtDpItemListByWhere("");
            for (int i = 0; i < vtdpitemlst.size(); i++) {
                VtDpItemEntity item = vtdpitemlst.get(i);
                vtdpitemlst.get(i).setVtdpname(item.getVtdpname() + " (民主评定处罚结果：" + item.getMzpdcllx() + " 组织评定处罚结果：" + item.getZzpdcllx() + ")");
            }

            model.addAttribute("vtdpitemlst", vtdpitemlst);

            VtDpUserListEntity entity = new VtDpUserListEntity();
            if (uservtdpid > 0) {
                entity = iVtDpUserService.GetUserVtDpByUservtdpid(uservtdpid);
            } else {
                entity.setUservtdpid(0L);
            }
            model.addAttribute("entity", entity);
        } catch (Exception ex) {

        }
        return "vtiondpline/user_vtdp_edit";
    }

    @RequestMapping(value = "/user_vtdp_gd_edit")
    public String UserVtdpGdEdit(Model model, Long userid, int status, Long uservtdpid) {
        try {
            UserEntity userentity = iUserService.GetUserById(userid);
            model.addAttribute("userentity", userentity);
            model.addAttribute("status", status);
            model.addAttribute("uservtdpid", uservtdpid);
        } catch (Exception ex) {

        }
        return "vtiondpline/user_vtdp_gd_edit";
    }

    @RequestMapping(value = "/add_vtdpuser")
    public String AddVtdpUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            Long uservtdpid = Long.parseLong(request.getParameter("uservtdpid"));
            String struserid = request.getParameter("userid");
            String strvtdpid = request.getParameter("vtdpid");
            String wgwjsm = request.getParameter("wgwjsm");

            String strbegintime = request.getParameter("begintime");
            String strendtime = request.getParameter("endtime");

            Long vtdpid = Long.parseLong(strvtdpid);
            Long userid = Long.parseLong(struserid);
            UserEntity user = this.GetUserById(userid);//拿到保存用户详细信息

            VtDpItemEntity vtdpitem = iVtDpItemService.GetVtDpItemListById(vtdpid);
            VtDpUserEntity vtdpuser = new VtDpUserEntity();
            vtdpuser.setUserid(userid);
            vtdpuser.setVtdpid(vtdpid);

            //固化开始
            vtdpuser.setSzdw(user.getSzdw());
            vtdpuser.setSzdwname(user.getOrgname());
            vtdpuser.setUserstatus(user.getUserstatus());
            vtdpuser.setRsgxszdw(user.getRsgxszdw());
            vtdpuser.setRsgxszdwname(user.getRsgxorgname());
            //固化结束

            vtdpuser.setStatus(0);
            vtdpuser.setByuserid(this.GetLoginUserId());
            vtdpuser.setWgwjsm(wgwjsm);
            vtdpuser.setByuserid(this.GetLoginUserId());

            //重新算结束时间
            int qxnum = vtdpitem.getQxnum();
            String qxdw = vtdpitem.getQxdw();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            Date dbegintime = formatter.parse(strbegintime);
            Date dendtime = formatter.parse(strendtime);//初始结束时间

            //按照规则重新设置结束时间
            Calendar cal = Calendar.getInstance();
            cal.setTime(dbegintime);

            if(qxdw.equals("月")){
                Integer add = qxnum;
                cal.add(Calendar.MONTH, add);
                dendtime = cal.getTime();
            }

            //计算结束时间
            if(qxdw.equals("季")){
                Integer qru = qxnum;
                Integer month = cal.get(Calendar.MONTH)+1;
                Integer add = 0;
                 if(month > 9) add = 12-month;
                else if(month > 6) add = 9 - month;
                else if(month > 3) add = 6 - month;
                else add = 3 - month;

                if(qru>1) add = add +(qru-1)*3;//跨季度加之

                cal.add(Calendar.MONTH, add);
                dendtime = cal.getTime();
            }
            if(qxdw.equals("年")){
                Integer year = qxnum;
                Integer month = cal.get(Calendar.MONTH)+1;
                Integer add = 12-month;
                if(year>1)add =add+(year-1)*12;
                cal.add(Calendar.MONTH, add);
                dendtime = cal.getTime();
            }

            vtdpuser.setBegintime(dbegintime);
            vtdpuser.setEndtime(dendtime);
            VtDpUserLogEntity vtdpuserlog = new VtDpUserLogEntity();
            vtdpuserlog.setStatus(0);
            vtdpuserlog.setUservtdplogdes("提交违规违纪项 ");
            vtdpuserlog.setByuserid(this.GetLoginUserId());

            int iResult = 0;
            if (uservtdpid > 0) {
                vtdpuser.setUservtdpid(uservtdpid);
                iResult = iVtDpUserService.UpdateVtDpUserEntity(vtdpuser);
            } else {
                iResult = iVtDpUserService.InseretVtdpUser(vtdpuser, vtdpuserlog);
            }
            return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
        } catch (Exception ex) {
            return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
        }
    }


    @RequestMapping(value = "/add_vtdpusergd")
    public String AddVtdpUserGd(HttpServletRequest request, HttpServletResponse response) {
        try {
            String struserid = request.getParameter("userid");
            String strstatus = request.getParameter("status");
            String struservtdpid = request.getParameter("uservtdpid");

            String uservtdpdes = request.getParameter("uservtdpdes");
            Date d = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
          uservtdpdes="<br/>"+sdf.format(d)+"  "+uservtdpdes;

            int status = Integer.parseInt(strstatus);
            Long userid = Long.parseLong(struserid);
            Long uservtdpid = Long.parseLong(struservtdpid);

            VtDpUserLogEntity entitylog = new VtDpUserLogEntity();
            entitylog.setStatus(status);
            entitylog.setUservtdpid(uservtdpid);
            entitylog.setUservtdplogdes(uservtdpdes);
            entitylog.setByuserid(this.GetLoginUserId());

            int iResult = 0;
            iResult = iVtDpUserService.UpdateVtdpUser(userid, entitylog);

            return renderStringScript(response, "<script>window.parent.CloseDialog(" + iResult + ")</script>");
        } catch (Exception ex) {
            return renderStringScript(response, "<script>window.parent.CloseDialog(0)</script>");
        }
    }


    @ResponseBody
    @RequestMapping(value = "/add_vtdpusertj")
    public ExceResult AddVtdpUserTj(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            String struserid = request.getParameter("userid");
            String strstatus = request.getParameter("status");
            String struservtdpid = request.getParameter("uservtdpid");

            String uservtdpdes = "";

            int status = Integer.parseInt(strstatus);
            Long userid = Long.parseLong(struserid);
            Long uservtdpid = Long.parseLong(struservtdpid);

            VtDpUserLogEntity entitylog = new VtDpUserLogEntity();
            entitylog.setStatus(status);
            entitylog.setUservtdpid(uservtdpid);
            entitylog.setUservtdplogdes(uservtdpdes);
            entitylog.setByuserid(this.GetLoginUserId());

            int iResult = 0;
            iResult = iVtDpUserService.UpdateVtdpUser(userid, entitylog);

            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_list")
    public LayTable<VtDpUserListEntity> GetList(HttpServletRequest request) {

        List<VtDpUserListEntity> lst = null;
        LayTable<VtDpUserListEntity> layTable = new LayTable<VtDpUserListEntity>();
        try {
            String year = request.getParameter("year");
            String orgid = request.getParameter("orgid");
            String realname = request.getParameter("realname");
            String where = "";
            String orgs ="";
            if (year != null && year.length() > 0) {
                where += " AND createtime>='" + year + "-01-01 00:00:00' AND createtime<='" + year + "-12-31 23:59:59' ";
            }

            if (orgid != null && orgid.length() > 0) {
//                OrgEntity orgentity = iOrgService.GetOrgById(Long.parseLong(orgid));
//                where += " AND userid IN (SELECT userid FROM t_sys_user  WHERE szdw IN (SELECT orgid FROM t_sys_org WHERE lft>=" + orgentity.getLft() + " AND lft<=" + orgentity.getRgt() + "))";
                List<OrgEntity> orgEntities = this.GetOrgListByOrgid(Long.parseLong(orgid));
                for (OrgEntity orgEntity : orgEntities) {
                    if (orgs.equals(""))
                        orgs = String.valueOf(orgEntity.getOrgid());
                    else
                        orgs += "," + orgEntity.getOrgid();
                }

            }
            if (orgs.length() > 0) {
                where += " AND szdw in (" + orgs + ")";
            }


            if (realname != null && realname.length() > 0) {
                where += " AND userid IN (SELECT userid FROM t_sys_user WHERE realname LIKE '%" + realname + "%') ";
            }

            where += this.GetUserListByRoleForNotUser();

            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            int beginrow = (page - 1) * limit;
            int endrow = limit;


            String limitwhere = where + " LIMIT " + beginrow + "," + endrow;

            lst = iVtDpUserService.GetUserVtDpList(limitwhere);
            for (int i = 0; i < lst.size(); i++) {
                int numr = (page - 1) * limit + (i + 1);
                lst.get(i).setRowNum(numr);
            }

            int iCount = iVtDpUserService.GetUserVtDpListCount(where);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }

    @LoginCheck(description = true)
    @ResponseBody
    @RequestMapping(value = "/get_gd_list")
    public LayTable<VtDpUserListEntity> GetGdList(HttpServletRequest request) {

        List<VtDpUserListEntity> lst = null;
        LayTable<VtDpUserListEntity> layTable = new LayTable<VtDpUserListEntity>();
        try {
            String year = request.getParameter("year");
            String orgid = request.getParameter("orgid");
            String realname = request.getParameter("realname");
            String where = "  ";
            String orgs = "";
            if (year != null && year.length() > 0) {
                where += " AND createtime>='" + year + "-01-01 00:00:00' AND createtime<='" + year + "-12-31 23:59:59' ";
            }

            if (orgid != null && orgid.length() > 0) {
//                OrgEntity orgentity = iOrgService.GetOrgById(Long.parseLong(orgid));
//                where += " AND userid IN (SELECT userid FROM t_sys_user  WHERE szdw IN (SELECT orgid FROM t_sys_org WHERE lft>=" + orgentity.getLft() + " AND lft<=" + orgentity.getRgt() + "))";
                List<OrgEntity> orgEntities = GetOrgListByOrgid(Long.valueOf(orgid));
                for (OrgEntity orgEntity : orgEntities) {
                    if (orgs.equals(""))
                        orgs = String.valueOf(orgEntity.getOrgid());
                    else
                        orgs += "," + orgEntity.getOrgid();
                }
            }

            if (orgs.length() > 0) {
                where += " AND szdw in (" + orgs + ")";
            }

            if (realname != null && realname.length() > 0) {
                where += " AND userid IN (SELECT userid FROM t_sys_user WHERE realname LIKE '%" + realname + "%') ";
            }

            where += this.GetUserListByRoleForNotUser();
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            int beginrow = (page - 1) * limit;
            int endrow = limit;

            where += " LIMIT " + beginrow + "," + endrow;

            lst = iVtDpUserService.GetUserVtDpList(where);
            for (int i = 0; i < lst.size(); i++) {
                int numr = (page - 1) * limit + (i + 1);
                lst.get(i).setRowNum(numr);

                if (lst.get(i).getRemark() != null) {

                    String remark = lst.get(i).getRemark();
                    if (remark.length() > 5) {

                        char first = remark.charAt(0);

                        if (String.valueOf(first).equals("<")) {
                            lst.get(i).setRemark(remark.substring(5, lst.get(i).getRemark().length()));

                        }


                    }


                }
            }

            int iCount = iVtDpUserService.GetUserVtDpListCount(where);
            layTable.setCode(0);
            layTable.setCount(iCount);
            layTable.setData(lst);

        } catch (Exception e) {
            layTable.setCode(500);
        }
        return layTable;
    }

    @ResponseBody
    @RequestMapping(value = "/delete_vtdpuser")
    public ExceResult DeleteVtdpUser(HttpServletRequest request, HttpServletResponse response) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);
        try {
            Long uservtdpid = Long.parseLong(request.getParameter("uservtdpid"));
            int iResult = iVtDpUserService.DeleteVtDpUser(uservtdpid);
            if (iResult > 0) {
                result.setCode(200);
                result.setResult(iResult);
                result.setMsg("操作成功");
            } else {
                result.setCode(300);
                result.setResult(iResult);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
        }
        return result;
    }
}
